tags:
- DSA
L6. Product of Array Except Self (Star)
Given an integer array nums
, return an array answer
such that answer[i]
is equal to the product of all the elements of nums
except nums[i]
.
The product of any prefix or suffix of nums
is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs on
Example1:
nums
= [1, 2, 3, 4]
[24, 12, 8, 6]
Example2:
nums
= [-1, 1, 0, -3, 3]
[0, 0, 9, 0, 0]
暴力方法需要循环遍历数组,时间复杂度来到了
前缀积 + 后缀积 时间复杂度空间复杂度都为
#include <iostream>
#include <vector>
class mySolution{
public:
std::vector<int> productExceptSelf(const std::vector<int> nums){
std::vector<int> answer(nums.size());
int prefix = 1;
for(int i = 0; i < nums.size(); i++){
answer[i] = prefix;
prefix *= nums[i];
}
int suffix = 1;
for(int i = nums.size() - 1; i >=0; --i){
answer[i] *= suffix;
suffix *= nums[i];
}
return answer;
}
};
int main(){
std::vector<int> nums{1, 2, 3, 4};
mySolution solution;
std::vector<int> answer = solution.productExceptSelf(nums);
for(auto elem : answer){
std::cout << elem << std::endl;
}
return 0;
}